<?php
declare(strict_types=1);

namespace App\Common\Service\Tool;

use App\Common\Service\BaseService;
use Hyperf\Context\Context;
use Hyperf\Logger\LoggerFactory;
use Mine\Exception\NormalStatusException;


class ElkService extends BaseService
{
    private $elkKey;

    public function __construct()
    {
        $this->elkKey = '--elkDivider--';
    }

    public function elk($file = '', $data = '')
    {
        if (empty($file)) {
            $file = 'default';
        }
        if (!in_array($file, array_keys(config('logger')))) {
            throw new NormalStatusException('请前往config/autoload/logger进行日志配置');
        }
        $obj = container()->get(LoggerFactory::class)->get('log', $file);
        return $obj->info($this->dealData($data));
    }

    public function dealData($data)
    {
        // 端口来源
        $source = Context::get(ConstantsService::API_SOURCE);

        // 用户id
        $userId = Context::get(ConstantsService::API_USER_ID_NAME);
        // 用户信息
        $userData = Context::get(ConstantsService::API_USER_DATA);

        $data['source'] = $source;
        $data['time_day'] = date('Y-m-d');
        $data['time'] = date('Y-m-d H:i:s', time());
        $data['time_int'] = time();
        $data['user_id'] = $userId ?? 0;
        $data['user_data'] = $userData ?? 0;

        $result = '';
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $v = json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            }
            if (is_object($v)) {
                $v = serialize($v);
            }

            $result .= $v . $this->elkKey;
        }

        return $result;
    }
}
